package com.wf.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.domain.AlipayDataDataserviceBillDownloadurlQueryModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wf.domain.PaymentManage;
import com.wf.domain.PaymentRecord;
import com.wf.domain.PropertyItem;
import com.wf.properties.AliPayProperties;
import com.wf.service.AlipayService;
import com.wf.service.PaymentManageService;
import com.wf.service.PaymentRecordService;
import com.wf.service.PropertyItemService;
import com.wf.utils.AliPayUtil;
import com.wf.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付宝支付实现类
 */
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AliPayUtil aliPayUtil;

    @Autowired
    private AliPayProperties aliPayProperties;

    @Autowired
    private PaymentManageService paymentManageService;

    @Autowired
    private PropertyItemService propertyItemService;

    @Autowired
    private PaymentRecordService paymentRecordService;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 创建支付宝支付链接
     *
     * @param orderId 订单ID，用于查询支付信息和配置支付参数
     * @return 支付宝支付页面的数据如果支付链接创建成功，返回支付页面的数据；否则返回null
     */
    public String create(String orderId) {

        // 创建支付宝支付模型对象，用于设置支付相关参数
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();

        // 获取缴费信息
        PaymentManage paymentManage = paymentManageService.getById(orderId);

        // 获取缴费项信息
        PropertyItem propertyItem = propertyItemService.getById(paymentManage.getType());


        // 设置商户订单号
        model.setOutTradeNo(String.valueOf(paymentManage.getManageId()));

        // 根据缴费项类型设置支付金额和主题
        if (propertyItem.getType() == 1) {
            // 类型1：按剂量计费
            model.setTotalAmount(String.valueOf(propertyItem.getPrice() * paymentManage.getDosage()));
        } else if (propertyItem.getType() == 2) {
            // 类型2：固定金额
            model.setTotalAmount(String.valueOf(propertyItem.getPrice()));
        }

        // 设置支付主题
        model.setSubject(propertyItem.getName());

        // 设置支付产品代码
        model.setProductCode(aliPayProperties.getProductCode());

        // 设置卖家ID
        model.setSellerId(aliPayProperties.getSellerId());

        // 获取支付页面数据
        String pageRedirectionData = aliPayUtil.appPay(model);

        return pageRedirectionData;

    }


    @Override
    public void notify(HttpServletRequest request) {


        Map<String, String> map = aliPayUtil.notifyServer(request);

        if (ObjectUtil.isNotEmpty(map)) {

            String trade_status = map.get("trade_status");
            //支付成功
            if (StrUtil.equals(trade_status, "TRADE_SUCCESS")) {
                log.info("[支付验证] 支付成功={}", JSONUtil.parse(map));
                PaymentRecord paymentRecord = new PaymentRecord();
                PaymentManage paymentManage = paymentManageService.getById(Integer.valueOf(map.get("out_trade_no")));
                paymentRecord.setPaymentType(paymentManage.getType());
                paymentRecord.setTradeNo(map.get("trade_no"));
                paymentRecord.setCreateDate(LocalDateTime.now());
                paymentRecord.setPaymentId(paymentManage.getManageId());
                paymentRecordService.save(paymentRecord);
            } else if (StrUtil.equals(trade_status, "TRADE_FINISHED")) {
                log.info("[支付验证] 交易完成={}", JSONUtil.parse(map));
            } else if (StrUtil.equals(trade_status, "TRADE_CLOSED")) {
                // 退款
                LambdaQueryWrapper<PaymentRecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(PaymentRecord::getPaymentId, map.get("out_trade_no"));
                paymentRecordService.remove(wrapper);
                // 修改payment_manage表中的id
                LambdaUpdateWrapper<PaymentManage> updateWrapper =
                        new LambdaUpdateWrapper<PaymentManage>()
                                .set(PaymentManage::getManageId, IdUtil.getSnowflakeNextId())
                                .set(PaymentManage::getIsDelete, 1)
                                .eq(PaymentManage::getManageId, map.get("out_trade_no"));
                paymentManageService.update(updateWrapper);
                log.info("[支付验证] 交易关闭={}", JSONUtil.parse(map));
            }
        }
    }

    @Override
    public void refund(String manageId) {


        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        //退款的订单Id，也可以设置流水号
        model.setOutTradeNo(manageId);
//        model.setTradeNo(tradeNo);
        // 获取缴费信息
        PaymentManage paymentManage = paymentManageService.getById(manageId);
        // 获取缴费项信息
        PropertyItem propertyItem = propertyItemService.getById(paymentManage.getType());
        //退款金额
        //==1代表按量交付
        if (propertyItem.getType() == 1) {
            model.setRefundAmount(String.valueOf(paymentManage.getDosage() * propertyItem.getPrice()));
        }
        //==1代表一次性交付
        else if ((propertyItem.getType() == 2)) {
            model.setRefundAmount(String.valueOf(propertyItem.getPrice()));
        }

        String refund = aliPayUtil.refund(model);
        log.info("[退款] 退款结果={}", JSONUtil.parse(refund));

    }

    @Override
    public String bill() {


        AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
//            model.setSmid("2088123412341234");
        model.setBillType("trade");
        model.setBillDate("2024-08-18");
        String url = aliPayUtil.bill(model);

        return url;

    }

    @Override
    public String tradeQuery(HashMap<String, Object> map) {



        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        if(ObjectUtil.isNotEmpty(map.get("out_trade_no")) )
        {
            model.setOutTradeNo(map.get("out_trade_no").toString());
        }
        if(ObjectUtil.isNotEmpty(map.get("trade_no")) )
        {
            model.setTradeNo(map.get("trade_no").toString());
        }
        // 设置查询选项
        List<String> queryOptions = new ArrayList<>();

        queryOptions.add("trade_settle_info");

        model.setQueryOptions(queryOptions);

        String body = aliPayUtil.queryTrade(model);

        return body;
    }


}